<!-- 会员操作弹框 -->
<template>
  <el-dialog
    custom-class="custom_dialog_box"
    :title="(enterType === 'add' ? '新增' : '修改') + '授权'"
    v-if="visible"
    :visible.sync="visible"
    width="780px"
    append-to-body
    destroy-on-close
    @close="dialogColse"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="90px"
      v-loading="submitLoading"
    >
      <el-alert
        class="custom_dialog_box_alert"
        title="基本信息"
        type="info"
        :closable="false"
      />
      <el-row>
        <el-col :span="12">
          <el-form-item label="会员名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入会员名称"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入联系方式"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="会员网站" prop="website">
            <el-input
              v-model="formData.website"
              placeholder="请输入会员网站"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员邮箱" prop="mail">
            <el-input
              v-model="formData.mail"
              placeholder="请输入会员邮箱"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="会员地址" prop="address">
        <el-input
          v-model="formData.address"
          placeholder="详细地址"
          maxlength="100"
        />
      </el-form-item>

      <el-alert
        class="custom_dialog_box_alert"
        title="会员展示"
        type="info"
        :closable="false"
      />
      <el-row>
        <el-form-item label="门店形象" prop="outsideUrl">
          <el-upload
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.outside"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'outsideUrl')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'outsideUrl')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="店内形象" prop="insideUrl">
          <el-upload
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.inside"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'insideUrl')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'insideUrl')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="特色展示" prop="characteristicUrl">
          <el-upload
            :class="{ 'hide_upload': formData.characteristicUrl }"
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :limit="1"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.characteristic"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'characteristicUrl')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) =>
                handleRemove(file, fileList, 'characteristicUrl')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="会员方案" prop="programmeUrls">
          <el-upload
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picBackObj.programme"
            :on-success="
              (res, file) => handleAvatarSuccess(res, file, 'programmeUrls')
            "
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'programmeUrls')
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- 图片查看弹框 -->
    <el-dialog :visible.sync="imgDialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="submitLoading">
        保 存
      </el-button>
      <el-button @click="dialogColse">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from "@/utils/auth";
import { UPLOADURL } from "@/api/useMenu/config";
import { customerSave, customerUpdate } from "@/api/useMenu/member";
export default {
  name: "AccreditHandleDialog",
  data() {
    return {
      visible: false, // 弹框状态
      // 表单数据
      formData: {},
      // 校验
      rules: {
        name: [
          {
            required: true,
            message: "请输入会员名称",
            trigger: ["blur", "change"],
          },
        ],
        website: [
          // {
          //   required: true,
          //   message: "请输入会员网站",
          //   trigger: "blur",
          // },
          {
            pattern:
              /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/,
            // /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/[\]@!\$&'\*\+,;=.]+$/
            message: "网址格式不正确",
            trigger: ["blur", "change"],
          },
        ],
        mail: [
          // {
          //   required: true,
          //   message: "请输入会员邮箱",
          //   trigger: "blur",
          // },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          // {
          //   required: true,
          //   message: "请输入手机号码",
          //   trigger: ["blur", "change"],
          // },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
        address: [
          // {
          //   required: true,
          //   message: "请输入详细地址",
          //   trigger: ["blur", "change"],
          // },
        ],
        outsideUrl: [
          {
            required: true,
            message: "请上传门店形象",
            trigger: "change",
          },
        ],
        insideUrl: [
          {
            required: true,
            message: "请上传店内形象",
            trigger: "change",
          },
        ],
        characteristicUrl: [
          {
            required: true,
            message: "请上传特色展示",
            trigger: "change",
          },
        ],
        programmeUrls: [
          // {
          //   required: true,
          //   message: "请上传会员方案",
          //   trigger: "change",
          // },
        ],
      },

      enterType: "", // 进入类型 add / edit

      // 上传参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + UPLOADURL,
      },

      // 图片详情弹框
      imgDialogVisible: false,
      dialogImageUrl: "",

      submitLoading: false,

      // 图片回写
      picBackObj: {
        inside: [], //店内形象
        outside: [], //门店形象
        characteristic: [], //特色展示
        programme: [], //会员方案
      },
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 打开弹框
    async openDialog(enterType = "add", row = {}) {
      this.visible = true;
      this.enterType = enterType;
      this.submitLoading = true;
      if (enterType === "edit") {
        this.formData = { ...row };
        let { insideUrl, outsideUrl, characteristicUrl, programmeUrls } = row;
        let inside = this.dealwithImgBack(insideUrl);
        let outside = this.dealwithImgBack(outsideUrl);
        let characteristic = this.dealwithImgBack(characteristicUrl);
        let programme = this.dealwithImgBack(programmeUrls);
        this.picBackObj = { inside, outside, characteristic, programme };
      }
      this.submitLoading = false;
    },

    dealwithImgBack(imgUrl) {
      let result = [];
      if (imgUrl) {
        let urlList = imgUrl.split(",");
        result = urlList.map(url => ({ url }));
      }
      return result;
    },

    // 上传成功
    handleAvatarSuccess(res, file, formKey) {
      let { msg } = res;
      let result = this.formData[formKey];
      if (result) {
        // 有值拼接
        result = result + "," + msg;
      } else {
        // 无值赋值
        result = msg;
      }
      this.$set(this.formData, formKey, result);
    },
    // 上传之前
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 20MB!");
      }
      return isLt2M;
    },
    handleRemove(file, fileList, formKey) {
      let urlList = fileList.map(item => item.response.msg);
      this.$set(this.formData, formKey, urlList.join(","));
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imgDialogVisible = true;
    },

    //  提交按钮
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          let { enterType, formData } = this;
          let request = enterType === "add" ? customerSave : customerUpdate;
          let { code, msg } = await request(formData);
          if (code === 200) {
            let msg = enterType === "add" ? "新增成功" : "修改成功";
            this.$modal.msgSuccess(msg);
            this.visible = false;
            this.$emit("updateTable");
          } else {
            this.$modal.msgError(msg || "接口异常");
          }
          this.submitLoading = false;
        }
      });
    },
    // Dialog 关闭的回调
    dialogColse() {
      this.visible = false;
      this.formData = {};
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .custom_dialog_box {
  &_alert {
    margin-bottom: 12px;
  }
  .el-dialog__body {
    max-height: 680px;
    overflow: auto;
  }
  .el-select {
    width: 100%;
  }
}

::v-deep .hide_upload {
  .el-upload {
    display: none;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
